<template>
  <div class="intelligence-graph-page">
    <div class="graph-content">
      <!-- 左侧筛选面板 -->
      <div class="filter-panel">
        <div class="filter-section">
          <h3>筛选条件</h3>

          <!-- 节点类型 -->
          <div class="filter-item">
            <label>节点类型:</label>
            <el-select
              v-model="filters.centerNode.type"
              @change="handleNodeTypeChange"
              clearable
              placeholder="全部"
            >
              <el-option
                v-for="type in filterOptions.nodeTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </div>

          <!-- 节点值 -->
          <div class="filter-item">
            <label>节点值:</label>
            <el-select
              v-model="filters.centerNode.value"
              @change="handleFilterChange"
              clearable
              placeholder="请选择节点值"
              :disabled="
                !filters.centerNode.type || filters.centerNode.type === 'all'
              "
            >
              <el-option
                v-for="node in filterOptions.nodeValues"
                :key="node"
                :label="node"
                :value="node"
              />
            </el-select>
          </div>

          <!-- 数据域 -->
          <div class="filter-item">
            <label>数据域:</label>
            <el-select
              v-model="filters.domains"
              @change="handleFilterChange"
              multiple
              clearable
              placeholder="全部"
            >
              <el-option
                v-for="domain in filterOptions.domains"
                :key="domain.code"
                :label="domain.name"
                :value="domain.code"
              />
            </el-select>
          </div>

          <!-- 最大深度 -->
          <div class="filter-item">
            <label>最大深度:</label>
            <el-select
              v-model="filters.maxDepth"
              @change="handleFilterChange"
              clearable
            >
              <el-option
                v-for="depth in filterOptions.maxDepths"
                :key="depth.value"
                :label="depth.label"
                :value="depth.value"
              />
            </el-select>
          </div>

          <!-- 风险等级 -->
          <div class="filter-item">
            <label>风险等级:</label>
            <el-select
              v-model="filters.severity"
              @change="handleFilterChange"
              multiple
              clearable
              placeholder="全部"
            >
              <el-option
                v-for="level in filterOptions.severityLevels"
                :key="level.value"
                :label="level.label"
                :value="level.value"
              >
                <span :style="{ color: level.color }">{{ level.label }}</span>
              </el-option>
            </el-select>
          </div>

          <!-- 时间范围 -->
          <div class="filter-item">
            <label>时间范围:</label>
            <el-select
              v-model="filters.timeRange"
              @change="handleFilterChange"
              clearable
            >
              <el-option
                v-for="range in filterOptions.timeRanges"
                :key="range.value"
                :label="range.label"
                :value="range.value"
              />
            </el-select>
          </div>

          <!-- 数据量限制 -->
          <div class="filter-item">
            <label>数据量限制:</label>
            <el-select
              v-model="filters.limit"
              @change="handleFilterChange"
              clearable
            >
              <el-option
                v-for="opt in filterOptions.limitOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </div>

          <div class="filter-actions">
            <el-button @click="resetFilters">重置</el-button>
            <el-button type="primary" @click="applyFilters">查询</el-button>
          </div>
        </div>

        <!-- 节点统计 -->
        <div class="statistics-section">
          <h3>节点统计</h3>
          <ul>
            <li>用户: {{ statistics.sourceCount }}个</li>
            <li>仓库: {{ statistics.intelligenceCount }}个</li>
            <li>文件: {{ statistics.assetCount }}个</li>
            <li>关键词: {{ statistics.cveCount }}个</li>
          </ul>
        </div>

        <!-- 图例 -->
        <div class="legend-section">
          <h3>图例</h3>
          <ul>
            <li>
              <span class="legend-icon user"></span>
              <span>用户</span>
            </li>
            <li>
              <span class="legend-icon repository"></span>
              <span>仓库</span>
            </li>
            <li>
              <span class="legend-icon file"></span>
              <span>文件</span>
            </li>
            <li>
              <span class="legend-icon keyword"></span>
              <span>关键词</span>
            </li>
          </ul>
        </div>
      </div>

      <!-- 中间图谱区域 -->
      <div class="graph-area">
        <div class="graph-toolbar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索节点..."
            @keyup.enter="searchNodes"
            class="search-input"
          >
            <template #append>
              <el-button @click="searchNodes"> 搜索 </el-button>
            </template>
          </el-input>

          <div class="graph-actions">
            <!-- <el-select
              v-model="currentLayout"
              @change="changeLayout"
              style="width: 120px; margin-right: 10px"
            >
              <el-option label="环形布局" value="circular" />
              <el-option label="力导向" value="force" />
            </el-select> -->

            <el-button @click="refreshGraph"> 刷新图谱 </el-button>
            <el-button @click="exportGraphPNG"> 导出图谱 </el-button>
            <!-- <el-button @click="autoLayout"> 自动布局 </el-button> -->
          </div>
        </div>

        <div class="graph-container">
          <DynamicGraph :nodes="graphNodes" :edges="graphEdges" />
        </div>
      </div>

      <!-- 节点详情对话框 -->
      <DynamicDetailDialog
        v-model="detailVisible"
        title="节点详情"
        :groups="detailGroups"
        :loading="loadingDetail"
        width="800px"
      >
        <template #footer>
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button
            v-if="nodeDetail.url"
            type="primary"
            @click="viewFullDetail"
          >
            打开链接
          </el-button>
        </template>
      </DynamicDetailDialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import { ElMessage } from "element-plus";
import DynamicDetailDialog from "@/components/DynamicDetailDialog";
import type { DetailGroup } from "@/components/DynamicDetailDialog/types";
import DynamicGraph from "@/components/DynamicGraph/index.vue";
import type { GraphNode, GraphEdge } from "@/components/DynamicGraph/types";
// API调用
import {
  getUnifiedGraphQuery,
  getUnifiedAvailableNodes,
  getUnifiedDomains,
  getUnifiedNodeDetail,
} from "../../servers";

// 页面状态
const username = ref("张三");
const activeTab = ref("intelligence");
const loading = ref(false);
const loadingDetail = ref(false);
const detailVisible = ref(false);
const nodeDetail = ref<any>({});
const searchKeyword = ref("");
const graphNodes = ref<GraphNode[]>([]);
const graphEdges = ref<GraphEdge[]>([]);

// 筛选条件
const filters = reactive({
  centerNode: {
    type: "", // 节点类型: department, keyword, ip, asset, all
    value: "", // 节点值
  },
  domains: [] as string[], // 数据域: ["pan_leak", "github_leak"]
  maxDepth: 2, // 最大深度: 1-3
  timeRange: "30d", // 时间范围: 7d, 30d, 90d
  severity: [] as string[], // 风险等级过滤: ["high", "critical"]
  limit: 50, // 限制节点数量，默认 50
});

// 筛选选项
const filterOptions = reactive({
  nodeTypes: [
    { value: "all", label: "全部" },
    { value: "department", label: "部门" },
    { value: "keyword", label: "关键词" },
    { value: "ip", label: "IP" },
    { value: "asset", label: "资产" },
  ],
  nodeValues: [] as string[], // 根据节点类型动态加载
  domains: [] as Array<{ code: string; name: string; is_active: boolean }>, // 数据域列表
  maxDepths: [
    { value: 1, label: "1层" },
    { value: 2, label: "2层" },
    { value: 3, label: "3层" },
  ],
  timeRanges: [
    { value: "7d", label: "最近7天" },
    { value: "30d", label: "最近30天" },
    { value: "90d", label: "最近90天" },
  ],
  severityLevels: [
    { value: "critical", label: "严重", color: "#ff4d4f" },
    { value: "high", label: "高危", color: "#faad14" },
    { value: "medium", label: "中危", color: "#ffd666" },
    { value: "low", label: "低危", color: "#52c41a" },
  ],
  limitOptions: [
    { value: 50, label: "50个节点" },
    { value: 100, label: "100个节点" },
    { value: 200, label: "200个节点" },
    { value: 500, label: "500个节点" },
  ],
});

// 统计数据
const statistics = reactive({
  sourceCount: 0,
  intelligenceCount: 0,
  assetCount: 0,
  cveCount: 0,
});

// 图谱数据已通过 graphNodes 和 graphEdges 管理

// 获取节点样式（转换为 DynamicGraph 需要的格式）
const getNodeStyle = (node: any) => {
  // 如果节点已经有style，直接使用
  if (node.style) {
    // 将 size 转换为数字（如果是数组，取平均值）
    let size = node.size || 30;
    if (Array.isArray(size)) {
      size = (size[0] + size[1]) / 2;
    }
    return {
      shape: "rect",
      size: size,
      color: node.style.fill || "#1890ff",
    };
  }

  // 否则根据类型设置默认样式
  const styles: any = {
    user: {
      shape: "rect",
      size: 60, // 平均尺寸
      color: "#1890ff",
    },
    repository: {
      shape: "rect",
      size: 70,
      color: "#722ed1",
    },
    file: {
      shape: "rect",
      size: 50,
      color: "#ff4d4f",
    },
    keyword: {
      shape: "rect",
      size: 40,
      color: "#fa8c16",
    },
  };

  // 根据严重程度设置文件节点颜色
  if (node.type === "file" && node.metadata?.severity) {
    const severity = node.metadata.severity;
    if (severity === "critical") {
      styles.file.color = "#ff4d4f";
    } else if (severity === "high") {
      styles.file.color = "#faad14";
    } else if (severity === "medium") {
      styles.file.color = "#ffd666";
    } else {
      styles.file.color = "#52c41a";
    }
  }

  return styles[node.type] || styles.file;
};

// 获取边样式（转换为 DynamicGraph 需要的格式）
const getEdgeStyle = (edge: any) => {
  // 如果边已经有style，直接使用
  if (edge.style) {
    return {
      color: edge.style.stroke || "#1890ff",
      width: edge.style.width || 2,
      lineStyle: edge.style.lineDash ? "dashed" : "solid",
    };
  }

  // 否则根据类型设置默认样式
  const styles: any = {
    owns: {
      color: "#a0c5e8",
      width: 2,
      lineStyle: "solid",
    },
    contains: {
      color: "#b37feb",
      width: 2,
      lineStyle: "solid",
    },
    matches: {
      color: "#ffd591",
      width: 2,
      lineStyle: "dashed",
    },
  };

  return styles[edge.type] || styles.owns;
};

// 转换API数据为 DynamicGraph 格式
const transformGraphData = (apiData: any) => {
  if (!apiData) {
    return { nodes: [], edges: [] };
  }

  const nodes = Array.isArray(apiData.nodes) ? apiData.nodes : [];
  const edges = Array.isArray(apiData.edges) ? apiData.edges : [];

  // 转换节点为 DynamicGraph 格式
  const graphNodes: GraphNode[] = nodes.map((node: any) => {
    const style = getNodeStyle(node);
    return {
      id: node.id,
      label: node.label || node.id,
      type: node.type,
      style: {
        color: style.color,
        shape: style.shape,
        size: style.size,
      },
      metadata: {
        ...node.metadata,
        severity: node.metadata?.severity,
      },
    };
  });

  // 转换边为 DynamicGraph 格式
  const graphEdges: GraphEdge[] = edges.map((edge: any, index: number) => {
    const style = getEdgeStyle(edge);
    return {
      id: edge.id || `edge_${index}`,
      label: edge.label || edge.type || "",
      source: edge.source,
      target: edge.target,
      type: edge.type,
      style: {
        color: style.color,
        lineStyle: style.lineStyle,
        width: style.width,
      },
      metadata: edge.metadata || {},
    };
  });

  return { nodes: graphNodes, edges: graphEdges };
};

// 更新图谱数据
const updateGraphData = (nodes: GraphNode[], edges: GraphEdge[]) => {
  graphNodes.value = nodes;
  graphEdges.value = edges;
};

// 加载图谱数据
const loadGraphData = async () => {
  try {
    loading.value = true;

    // 构建请求参数（根据统一知识图谱接口文档格式）
    const params: any = {
      time_range: filters.timeRange,
      limit: filters.limit,
      max_depth: filters.maxDepth,
    };

    // 如果有中心节点，添加 center_node
    if (filters.centerNode.type && filters.centerNode.type !== "all") {
      if (filters.centerNode.value) {
        params.center_node = {
          type: filters.centerNode.type,
          value: filters.centerNode.value,
        };
      }
    }

    // 如果有选中的域，添加 domains
    if (filters.domains.length > 0) {
      params.domains = filters.domains;
    }

    // 如果有风险等级过滤，添加 severity_filter
    if (filters.severity.length > 0) {
      params.severity_filter = filters.severity;
    }

    const res = await getUnifiedGraphQuery(params);
    if (res.code === 2000) {
      const { nodes, edges } = transformGraphData(res.data);

      // 更新统计数据（从接口响应中获取）
      if (res.data.statistics) {
        statistics.sourceCount =
          res.data.statistics.node_types?.department || 0;
        statistics.intelligenceCount =
          res.data.statistics.node_types?.repository || 0;
        statistics.assetCount = res.data.statistics.node_types?.file || 0;
        statistics.cveCount = res.data.statistics.node_types?.keyword || 0;
      }

      // 更新图谱数据
      await nextTick();
      if (nodes.length > 0) {
        updateGraphData(nodes, edges);
      } else {
        ElMessage.warning("暂无数据");
        graphNodes.value = [];
        graphEdges.value = [];
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取图谱数据失败");
  } finally {
    loading.value = false;
  }
};

// 获取可用节点列表
const loadAvailableNodes = async () => {
  try {
    const res = await getUnifiedAvailableNodes();
    if (res.code === 2000 && res.data?.node_types) {
      // 更新节点类型选项（如果接口返回了类型列表）
      // 这里可以根据实际返回的数据结构来更新 filterOptions.nodeTypes
    }
  } catch (error: any) {
    console.error("获取可用节点列表失败:", error);
  }
};

// 获取数据域列表
const loadDomains = async () => {
  try {
    const res = await getUnifiedDomains();
    if (res.code === 2000 && res.data?.domains) {
      filterOptions.domains = res.data.domains.filter((d: any) => d.is_active);
    }
  } catch (error: any) {
    console.error("获取数据域列表失败:", error);
  }
};

// 节点类型变化时，加载对应的节点值列表
const handleNodeTypeChange = async () => {
  // 清空节点值
  filters.centerNode.value = "";
  filterOptions.nodeValues = [];

  // 如果选择了"全部"，不需要加载节点值
  if (!filters.centerNode.type || filters.centerNode.type === "all") {
    return;
  }

  try {
    const res = await getUnifiedAvailableNodes();
    if (res.code === 2000 && res.data?.node_types) {
      const nodeType = res.data.node_types.find(
        (nt: any) => nt.type === filters.centerNode.type
      );
      if (nodeType && nodeType.nodes) {
        filterOptions.nodeValues = nodeType.nodes;
      }
    }
  } catch (error: any) {
    console.error("获取节点值列表失败:", error);
  }
};

// 节点点击事件处理（需要在 DynamicGraph 组件中支持事件传递）
// 暂时保留，等待 DynamicGraph 组件支持事件
const handleNodeClick = async (node: GraphNode) => {
  try {
    loadingDetail.value = true;
    const res = await getUnifiedNodeDetail({
      node_id: node.id,
      node_type: node.type,
    });

    if (res.code === 2000) {
      nodeDetail.value = res.data;
      detailVisible.value = true;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取节点详情失败");
  } finally {
    loadingDetail.value = false;
  }
};

// 搜索节点（通过重新加载图谱数据实现）
const searchNodes = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  // 使用关键词作为中心节点进行查询
  filters.centerNode.type = "keyword";
  filters.centerNode.value = searchKeyword.value;
  loadGraphData();
};

// 刷新图谱
const refreshGraph = () => {
  loadGraphData();
};

// 导出图谱PNG（暂时移除，DynamicGraph组件需要添加导出功能）
const exportGraphPNG = () => {
  ElMessage.info("导出功能待实现");
};

// 导出JSON数据（使用当前图谱数据）
const exportGraphJSON = async () => {
  try {
    if (graphNodes.value.length === 0) {
      ElMessage.warning("暂无图谱数据");
      return;
    }

    const exportData = {
      nodes: graphNodes.value.map((node) => ({
        id: node.id,
        label: node.label,
        type: node.type,
        metadata: node.metadata,
      })),
      edges: graphEdges.value.map((edge) => ({
        source: edge.source,
        target: edge.target,
        type: edge.type,
        label: edge.label,
      })),
    };

    // 创建下载链接
    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: "application/json",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `github_graph_${new Date().getTime()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success("JSON数据导出成功");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出JSON数据失败");
  }
};

// 筛选相关方法
const handleFilterChange = () => {
  // 可以在这里添加防抖处理
};

const applyFilters = () => {
  loadGraphData();
};

const resetFilters = () => {
  filters.centerNode.type = "";
  filters.centerNode.value = "";
  filters.domains = [];
  filters.maxDepth = 2;
  filters.timeRange = "30d";
  filters.severity = [];
  filters.limit = 50;
  searchKeyword.value = "";
  filterOptions.nodeValues = [];

  // 重新加载数据
  loadGraphData();
};

// 节点详情页操作
const viewFullDetail = () => {
  // 打开链接
  if (nodeDetail.value?.url) {
    window.open(nodeDetail.value.url, "_blank");
  } else {
    ElMessage.warning("暂无链接");
  }
};

// 详情分组数据（根据实际接口返回的数据结构）
// 接口返回: { leak_count: 1, url: "https://github.com/facebook/react-internal" }
const detailGroups = computed<DetailGroup[]>(() => {
  if (!nodeDetail.value || Object.keys(nodeDetail.value).length === 0) {
    return [];
  }

  const detail = nodeDetail.value;

  // 根据实际返回的数据结构显示
  return [
    {
      title: "基本信息",
      type: "normal" as const,
      items: [
        {
          key: "url",
          label: "地址",
          value: detail.url || "-",
          span: 2,
        },
        {
          key: "leak_count",
          label: "泄露数量",
          value: detail.leak_count ?? 0,
        },
      ],
    },
  ];
});

// 辅助方法：根据评分或严重程度获取标签类型
const getSeverityType = (scoreOrSeverity: number | string) => {
  if (typeof scoreOrSeverity === "number") {
    if (scoreOrSeverity >= 9.0) return "danger";
    if (scoreOrSeverity >= 7.0) return "warning";
    if (scoreOrSeverity >= 4.0) return "info";
    return "success";
  }
  // 字符串类型（如 "critical", "high", "medium", "low"）
  const severity = String(scoreOrSeverity).toLowerCase();
  if (severity === "critical" || severity === "high") return "danger";
  if (severity === "medium") return "warning";
  return "info";
};

// 辅助方法：根据风险评分获取标签类型
const getRiskType = (score: number) => {
  if (score >= 80) return "danger";
  if (score >= 60) return "warning";
  if (score >= 40) return "info";
  return "success";
};

// 初始化
onMounted(async () => {
  // 等待组件初始化完成
  await nextTick();

  // 加载选项数据
  await Promise.all([loadDomains(), loadAvailableNodes()]);

  // 加载图谱数据
  await loadGraphData();
});

// 暴露方法供父组件调用
defineExpose({
  refreshGraph,
});
</script>

<style scoped lang="scss">
.intelligence-graph-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.navbar-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .navbar-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: #333;
    }

    .user-info {
      color: #666;
      font-size: 14px;
    }
  }
}

.tabs-container {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 10px 20px 0;
}

.graph-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 150px);
}

.filter-panel {
  width: 280px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;

  label {
    font-size: 14px;
    color: #666;
    font-weight: 500;
  }

  .el-select,
  .el-input {
    width: 100%;
  }
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.statistics-section,
.legend-section {
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 12px;

  h3 {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 500;
  }

  ul {
    list-style: none;
    padding: 0;
    margin: 0;

    li {
      font-size: 13px;
      color: #666;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.legend-icon {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;

  &.user {
    background-color: #1890ff;
  }

  &.repository {
    background-color: #722ed1;
    border-radius: 2px;
  }

  &.file {
    background-color: #ff4d4f;
    border-radius: 2px;
  }

  &.keyword {
    background-color: #fa8c16;
    border-radius: 2px;
  }
}

.graph-area {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 800px;
  height: 0; // 配合 flex: 1 使用，确保容器有高度
}

.graph-toolbar {
  padding: 10px 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.graph-actions {
  display: flex;
  align-items: center;
  gap: 5px;
}

.graph-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.detail-panel {
  width: 400px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.detail-header {
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }

  .close-btn {
    color: #999;
  }
}

.detail-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;

  .detail-section {
    margin-top: 16px;

    h4 {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;
    }
  }

  .detail-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
  }
}

.el-table {
  font-size: 12px;

  .el-table__cell {
    padding: 6px 0;
  }
}

.el-descriptions {
  margin-bottom: 16px;

  .el-descriptions__label {
    font-weight: 500;
  }
}

@media (max-width: 1600px) {
  .filter-panel {
    width: 240px;
  }

  .detail-panel {
    width: 350px;
  }

  .search-input {
    width: 220px;
  }
}
</style>
